$(function() {
	if (navigator.userAgent.indexOf("MSIE") > 0) {
		document.getElementById('selLevel').style.width = 25 + 'px';
		document.getElementById('selState').style.width = 25 + 'px';
	}

	if (navigator.userAgent.indexOf("Firefox") > 0) {
		document.getElementById('selLevel').style.width = 31 + 'px';
		document.getElementById('selState').style.width = 31 + 'px';
	}
	var http = new XMLHttpRequest;
	http.open("HEAD", ".", false);
	http.send(null);
	var today = new Date(http.getResponseHeader("Date"));
	var year_today = today.getFullYear();
	var month_today = (today.getMonth() + 1) < 10 ? "0" + (today.getMonth() + 1) : (today.getMonth() + 1);
	// var day = today.getDate() < 10 ? "0" + today.getDate() : today.getDate();
	var time = year_today + '-' + month_today;

	$.ajax({
		url: '/api/role/user?',
		type: 'GET',
		data: {'_t':new Date().getTime()},
		success: function(data) {
			//	console.info('data', data);
			var flag = false;
			for (var i = 0; i < data.length; i++) {
				if (data[i].roleName == '高层领导' || data[i].roleName == '部门经理' || data[i].roleName == 'admin') {
					flag = true;
				}
			}
			//console.info(flag);
			if (!flag) {
				$('#surePer').attr('type', 'hidden');
			} else {
				$('#surePer').attr('type', 'button');
			}
		},
		error: function(data) {
			alert('error');
		}
	});


	//统计绩效未填写数
	$("#writeMsg").click(function() {
		// alert("1111111");
		$("#showUnwrite").modal('show');

	});
	//统计绩效未审核数
	$("#checkMsg").click(function() {
		// alert("2222222");
		var time = $("#searchTime").val();
		dataPage(1, "", time, "未审核");
	});
	//统计优秀率
	$("#statisticA").click(function() {
		$("#showARatio").modal('show');
	});
	//根据状态查询
	$("#selState").change(function() {
		var staVal = $("#selState option:selected").val();
		var keyword = $("#keyword").val();
		var staKey = "";
		var time = $("#searchTime").val();
		if (staVal == 0) {
			staKey = "未审核";
		} else if (staVal == 1) {
			staKey = "未确认";
		} else if (staVal == 2) {
			staKey = "已确认";
		}
		document.getElementById("keywordExcel").value = staKey; //把搜索放到固定位置，导出用到
		dataPage(1, keyword, time, staKey);

	});
	//根据绩效等级查询
	$("#selLevel").change(function() {
		var levelVal = $("#selLevel option:selected").text();
		var keyword = $("#keyword").val();
		var time = $("#searchTime").val();
		if(levelVal == "全部") {
			levelVal = "";
		}
		document.getElementById("keywordExcel").value = levelVal;
		dataPage(1,keyword,time,levelVal);
	});

	//初始化时间选择器
	$('#searchTime').datepicker({
		autoclose: true,
		// todayBtn: true,
		startView: 1,
		minViewMode: 1
	});
	var expoertData = [];
	var showListData;
	// var today = new Date();
	// var year_today = today.getFullYear();
	// var month_today = (today.getMonth() + 1) < 10 ? "0" + (today.getMonth() + 1) : (today.getMonth() + 1);

	var dataPage = function(cpage, keyword, time, levSta) {
		// $("#employeeRecord").html('');

		if (cpage == 1) {
			//统计绩效未填写及未审核数据
			$.ajax({
				url: '/api/statistics/performance/statisPerf?',
				type: 'get',
				data: {'time': time, '_t':new Date().getTime()},
				success: function(result) {
					// console.info("writeMsg--result:", result);
					var unwriteData = result.unwrite;
					var uncheckData = result.uncheck;
					if (unwriteData != null && unwriteData != undefined) {
						$("#writeMsg").html("（未填写:" + unwriteData.length + "人；");
						showCounts(unwriteData, 0);
					}
					if (uncheckData != null && uncheckData != undefined) {
						$("#checkMsg").html("未审核:" + uncheckData[0].num + "人）");
					}
				}
			});

			$.ajax({
				url: '/api/statistics/organization/countRatio?',
				type: 'get',
				data: {'time': time, '_t':new Date().getTime()},
				success: function(result) {
					// console.info("countRatio:",result);
					showCounts(result, 1);
				}
			});
		}

		// var pageSize = $("#pageSize option:selected").text();
		var pageSize = 15;
		$.ajax({
			url: '/api/statistics?',
			type: 'GET',
			data: {'pageSize': pageSize,'cpage':cpage, 'keyword':keyword, 'time': time, 'levSta':levSta, '_t':new Date().getTime()},
			success: function(data) {
				// console.info('dada',data);
				expoertData = data.rows;
				showListData = data.data;
				// console.info(data.data);
				$("#staticticsBody").html('');
				// console.info('dataaaa:', data.data);
				// $("#showCount").html("共"+ data.count + "条记录");
				if (data.count < pageSize) {
					page = 1;
				} else {
					page = Math.ceil(data.count / pageSize);
					//console.info('page:',page);
				}
				var options = {
					currentPage: cpage,
					totalPages: page,
					alignment: 'right',
					count: data.count,
					selectorId: 'pageSeletct',
					onPageChanged: function(e, oldPage, newPage) {
						dataPage(newPage, keyword, time, levSta);
					}
				};
				$('#paginator').bootstrapPaginator(options);
				$("#pageSeletct").change(function() {
					var page = $("#pageSeletct option:selected").val();
					$('#paginator').bootstrapPaginator("show",page);
				});
				$.ajax({
					url: '/api/role/user?',
					type: 'GET',
					data: {'_t': new Date().getTime()},
					success: function(data) {
						for (var i = 0; i < data.length; i++) {
							if (data[i].roleName == '部门经理') {
								$.ajax({
									url: '/api/organizations/selOrgByUser?',
									type: 'GET',
									data: {'_t':new Date().getTime()},
									success: function(data) {
										// console.info("data--------",data);
										showList(showListData, data);
									},
									error: function(data) {
										alert('error');
									}
								});
							}else{
								showList(showListData, "");
							}
						}
					},
					error: function(data) {
						alert('error');
					}
				});
				// 	var data = data.data;
				// 	if (data.length == 0) {
				// 		$('#tip').html("<div class='alert alert-warning' style='margin-top:-20px;'>未能搜索到相关信息</div>");
				// 		return;
				// 	} else {
				// 		$('#tip').html("");
				// 	}
				// 	for (var i = 0; i < data.length; i++) {
				// 		if (data[i].state == '1' && data[i].superior != data[i].lastChange)
				// 			data[i].superior = data[i].lastChange;
				// 		if (data[i].comment == null)
				// 			data[i].comment = '';
				// 		if (data[i].score == null) {
				// 			data[i].score = 0;
				// 			data[i].level = "E";
				// 		}

				// 		$("#staticticsBody").append('<tr><td class="center">' + (i + 1) + '</td><td class="center">' + changeNull(data[i].orgName) + '</td><td class="center">' + changeNull(data[i].projectOrg) + '</td><td class="center">' + changeNull(data[i].project) + '</td><td class="center"><a href="/performanceAudit/staffAudit/' + changeNull(data[i].perId) + '">' + changeNull(data[i].employeeName) + '</a></td><td class="center">' + changeNull(data[i].superior) + '</td><td class="center">' + changeNull(data[i].score) + '</td><td class="center">' + changeNull(data[i].level) + '</td><td class="center">' + changeNull(data[i].comment) + '</td></tr>');
				// 	}
			},
			error: function(data) {
				$('#tip').html("<div class='alert alert-warning' style='margin-top:-20px;'>未能搜索到相关信息</div>");
			}
		});
	};

	var showCounts = function(data, type) {
		if (type == 0) {
			$("#unwriteTbd").html("");
			if (data == null || data.length == 0) {
				$('#unwriteTip').html("<div class='alert alert-warning' style='margin-top:-20px;'>未能搜索到相关信息</div>");
				return;
			} else {
				$('#unwriteTip').html("");
			}
			$.each(data, function(i, unwriteItem) {
				var templateData = {
					num: i + 1,
					empName: unwriteItem.name,
					orgName: unwriteItem.orgName + "-" + unwriteItem.orgAddress
				};
				var template = "<tr><td class='center'>{{num}}</td>" +
					"<td class='center'>{{empName}}</td>" +
					"<td class='center'>{{orgName}}</td></tr>";
				var $html = $(Mustache.to_html(template, templateData));
				$("#unwriteTbd").append($html);

			});
		} else if (type == 1) {
			$("#ratioTbd").html("");
			if (data == null || data.length == 0) {
				$('#ratioTip').html("<div class='alert alert-warning' style='margin-top:-20px;'>未能搜索到相关信息</div>");
			} else {
				$("#ratioTip").html("");
			}
			$.each(data, function(i, item) {
				var templateData = {
					num: i + 1,
					deptName: item.deptName + "-" + item.deptAddr,
					ratio: item.ratio + "%"
				};
				var template = "<tr><td class='center'>{{num}}</td>" +
					"<td class='center'>{{deptName}}</td>" +
					"<td class='center'>{{ratio}}</td></tr>";
				var $html = $(Mustache.to_html(template, templateData));
				$("#ratioTbd").append($html);
			});
		}

	}


	var showList = function(data, dept) {
		$("#staticticsBody").html("");
		if (data == null || data.length == 0) {
			$('#tip').html("<div class='alert alert-warning' style='margin-top:-20px;'>未能搜索到相关信息</div>");
			return;
		} else {
			$('#tip').html("");
		}
		$.each(data, function(i, item) {
			// console.info('item', item);
			if (item.score == null) {
				item.score = 0;
				item.level = "E";
			}
			// if (item.state == '1') {
			// 	item.superior = item.lastChange;
			// }
			if (item.state == 0) {
				item.state = '未审核';
			} else if (item.state == 1) {
				item.state = '未确认';
			} else if (item.state == 3) {
				item.state = '退回重审';
			} else if (item.state == 2) {
				item.state = '已确认';
			}
			var templateData = {
				orgName: changeNull(item.orgName),
				projectOrg: changeNull(item.projectOrg),
				project: changeNull(item.project),
				perId: item.perId,
				employeeName: changeNull(item.employeeName),
				superior: changeNull(item.superior),
				score: item.score,
				level: item.level,
				comment: changeNull(item.comment),
				perfDate: item.perfDate,
				state: item.state
			};
			var dateArr = (item.perfDate).split("-");
			var disabledFlag = "disabled";
			if (dept != undefined) {
				for (var j = 0; j < dept.length; j++) {
					// console.info(item.orgName + "-------" + dept[j].orgName);
					if (item.departmentId == dept[j].id) {
						disabledFlag = "";
					}
				}
			}
			var template;
			if (dateArr[0] == year_today && dateArr[1] == month_today) {
				template = '<tr><td class="center" style="width:3%;word-wrap:break-word;vertical-align:middle;"><label><input type="checkbox" name="check" ' + disabledFlag + '><span class="lbl"></span></label><td style="display:none">{{perId}}</td></td><td class="center" style="width:5%;word-wrap:break-word;vertical-align:middle;"><input type="hidden"  id="perId" name="perId" value="{{perId}}"/>' + (i + 1) + '</td>' +
					'<td class="center" style="width:10%;word-wrap:break-word;vertical-align:middle;"><input type="hidden" id="perfDate" name="perfDate" value="{{perfDate}}"/>{{orgName}}</td>' +
					'<td class="center" style="width:10%;word-wrap:break-word;vertical-align:middle;">{{projectOrg}}</td>' +
					'<td class="center" style="width:14%;word-wrap:break-word;vertical-align:middle;">{{project}}</td>' +
					'<td class="center" style="width:8%;word-wrap:break-word;vertical-align:middle;" id="showUpdate"><a href="#">{{employeeName}}</a></td>' +
					'<td class="center" style="width:10%;word-wrap:break-word;vertical-align:middle;">{{superior}}</td>' +
					'<td class="center" style="width:5%;word-wrap:break-word;vertical-align:middle;">{{score}}</td>' +
					'<td class="center" style="width:7%;word-wrap:break-word;vertical-align:middle;">{{level}}</td>' +
					'<td class="center" style="width:10%;word-wrap:break-word;vertical-align:middle;">{{state}}</td>' +
					'<td class="center" style="width:18%;word-wrap:break-word;vertical-align:middle;">{{comment}}</td></tr>';
			} else {
				template = '<tr><td class="center" style="width:3%;word-wrap:break-word;vertical-align:middle;"><label><input type="checkbox" name="check" ' + disabledFlag + '><span class="lbl"></span></label><td style="display:none">{{perId}}</td></td><td class="center" style="width:5%;word-wrap:break-word;vertical-align:middle;"><input type="hidden"  id="perId" name="perId" value="{{perId}}"/>' + (i + 1) + '</td>' +
					'<td class="center" style="width:10%;word-wrap:break-word;vertical-align:middle;"><input type="hidden" id="perfDate" name="perfDate" value="{{perfDate}}"/>{{orgName}}</td>' +
					'<td class="center" style="width:10%;word-wrap:break-word;vertical-align:middle;">{{projectOrg}}</td>' +
					'<td class="center" style="width:14%;word-wrap:break-word;vertical-align:middle;">{{project}}</td>' +
					'<td class="center" style="width:8%;word-wrap:break-word;vertical-align:middle;" id="showUpdate">{{employeeName}}</td>' +
					'<td class="center" style="width:10%;word-wrap:break-word;vertical-align:middle;">{{superior}}</td>' +
					'<td class="center" style="width:5%;word-wrap:break-word;vertical-align:middle;">{{score}}</td>' +
					'<td class="center" style="width:7%;word-wrap:break-word;vertical-align:middle;">{{level}}</td>' +
					'<td class="center" style="width:10%;word-wrap:break-word;vertical-align:middle;">{{state}}</td>' +
					'<td class="center" style="width:18%;word-wrap:break-word;vertical-align:middle;">{{comment}}</td></tr>';
			}

			// template = '<tr><td class="center"><input type="hidden" id="perId" name="perId" value="{{perId}}"/>' + (i + 1) + '</td>'+
			//                 '<td class="center"><input type="hidden" id="perfDate" name="perfDate" value="{{perfDate}}"/>{{orgName}}</td>'+
			//                 '<td class="center">{{projectOrg}}</td>'+
			//                 '<td class="center">{{project}}</td>'+
			//                 '<td class="center" id="showUpdate">{{employeeName}}</td>'+
			//                 '<td class="center">{{superior}}</td>'+
			//                 '<td class="center">{{score}}</td>'+
			//                 '<td class="center">{{level}}</td>'+
			//                 '<td class="center">{{comment}}</td></tr>';
			var $html = $(Mustache.to_html(template, templateData));
			$("#staticticsBody").append($html);

			$html.find('#showUpdate').click({
				html: $html
			}, function(e) {
				var $html = $(e.data.html);
				var id = $html.find('#perId').val();
				var perfDate = $html.find('#perfDate').val();
				// var dateArr = perfDate.split("-");
				if (dateArr[0] == year_today && dateArr[1] == month_today) {
					var cpage = $("#pageSeletct option:selected").val();
					var key = {
						time: $('#searchTime').val(),
						keyword : $('#keyword').val(),
						levSta: $("#keywordExcel").val()
					};
					key = encodeURIComponent(JSON.stringify(key));
					window.location.href = "/performanceAudit/staffManagerAudit?perfId=" + id + "&cpage=" + cpage + "&key=" + key;
				} else {
					return;
				}
				// console.log(id + "---" + perfDate);
			});

			// $html.find('#editIcon').click({
			// 	html: $html
			// }, function(e) {

			// 	var $html = $(e.data.html);

			// 	// var code = $html.find('#code').html();
			// 	var name = $html.find('#name').html();
			// 	var personid = $html.find('#hiderespid').val();
			// 	var resp = $html.find('#resp').html();
		});
	};

	var changeNull = function(string) {
		if (string == null)
			return "";
		else
			return string;
	};


	$('#searchTime').val(time);

	var hisPage = $("#hisPage").val();
	var key = $("#getKey").val();
	var keyword = "";
	var searchTime = time;
	var levSta = "";
	if(key != "" && key != 0 && key != null && key != undefined) {
		key = JSON.parse(decodeURIComponent(key));
		// console.info("key", key);
		keyword = key.keyword;
		searchTime = key.time;
		levSta = key.levSta;
		$("#keyword").val(keyword);
		$("#searchTime").val(searchTime);
		$("#keywordExcel").val(levSta);

	}
	if(hisPage == "" || hisPage == 0 || hisPage == null || hisPage == undefined) {
		dataPage(1, keyword, searchTime, levSta);
	}else{
		dataPage(hisPage, keyword, searchTime, levSta);
	}
	// dataPage(1, "", time, "");

	$('#pageSize').change(function() {
		$("#staticticsBody").html('');
		dataPage(1, "", time, "");
	});
	$('#searchBtn').click(function() {
		$('#staticticsBody').html('');
		var time = $('#searchTime').val();
		var keyword = $('#keyword').val();
		dataPage(1, keyword, time, "");
	});
	//搜索输入框回车事件
	$("#keyword").keydown(function(e) {
		if(e.keyCode == 13) {
			$('#searchBtn').click();
		}
	});

	$("#exportPerformance").click(function() {
		if (expoertData.length > 0) {
			var time = $("#searchTime").val();
			var keywordExcel = $("#keywordExcel").val();
			var keyword = $('#keyword').val();
			var url = "/api/statistics/exportExcel?keyword=" + keyword +"&time=" + time+'&levSta=' + keywordExcel;
			window.location = url;
		}
	});

	//checkId 全选与反选
	$('table th input:checkbox').on('click', function() {
		var that = this;
		$(this).closest('table').find('tr > td:first-child input:checkbox')
			.each(function(item) {
				if (!this.disabled) {
					this.checked = that.checked;
				}
			});
	});

	$('#surePer').click(function() {
		var checks = $("input[name='check']");
		// console.info('obj', $("input[name='check']:checked").length);
		var cids = "";
		if ($("input[name='check']:checked").length === 0) {
			bootbox.alert('请选择行！');
			return;
		}
		bootbox.confirm("确定要确认勾选项吗?", function(result) {
			if (!result) {
				return;
			}
			var ids = [];
			$.each(checks, function(index, e) {
				if ($(e).is(":checked")) {
					var cid = $("#table_bug_report tr:eq(" + (index + 1) + ") td:eq(1)").text();
					// var depaName = $("#table_bug_report tr:eq(" + (index + 1) + ") td:eq(3)").text();
					var state = $("#table_bug_report tr:eq(" + (index + 1) + ") td:eq(10)").text();
					var data = {
						cid: cid,
						state: state
						// depaName: depaName
					}
					ids.push(data);
				}
			});
			//遍历获取到的值，如果有未审核的绩效则不能确认
			var flag = false;
			// var flagDep = false;
			// if (depManagName == undefined) {
			// 	flagDep = true;
			// }
			for (var i = 0; i < ids.length; i++) {
				if (ids[i].state == '未审核' || ids[i].state == '退回重审') {
					flag = true;
				}
				// if (depManagName != undefined) {
				// 	for (var j = 0; j < depManagName.length; j++) {
				// 		if (ids[i].depaName != depManagName[j].orgName) {
				// 			flagDep = true;
				// 		}
				// 	}
				// }
			}
			// if (flagDep) {
			// 	bootbox.alert('您只能确认您所负责部门员工的绩效！');
			// 	return;
			// }
			if (flag) {
				bootbox.alert('勾选行有【未被审核/退回重审】的绩效,不能确认！');
				return;
			}

			//遍历获取到的值，如果有未审核的绩效则不能确认
			var flag_ = false;
			var perfIds = [];
			for (var i = 0; i < ids.length; i++) {
				if (ids[i].state == '已确认') {
					flag_ = true;
				}
				perfIds.push(ids[i].cid * 1);
			}
			if (flag_) {
				bootbox.alert('勾选行有已确认绩效,无需再次确认！');
				return;
			}


			var idData = {
				ids: perfIds
			};
			// console.info('perfId', idData);
			makeSure(idData);
		});
	});

	var makeSure = function(idData) {
		$.ajax({
			url: '/api/performance/state',
			type: 'put',
			data: idData,
			success: function(result) {
				if (result == 'noPrivilege') {
					bootbox.alert('您没有权限,操作失败！');
					return;
				}
				bootbox.alert('确认成功！', function() {

					window.location.href = '/statistics';

				});
			},
			error: function(result) {
				bootbox.alert('确认失败！');
			}
		});
	};

});